/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class ClientCustomSSL {
	public static String Wechatrefund(HttpServletRequest request, String data,String trade_type) throws Exception{
		
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		System.out.println("))))))))))))))))"+request.getSession().getServletContext().getRealPath("/"));
		String file_name = "";
		
		if("APP".equals(trade_type)){
			file_name = ConfigUtil.CERT_PATH_APP;
       	}else{
       		file_name = ConfigUtil.CERT_PATH_WECHAT;
		}
        FileInputStream instream = new FileInputStream(new File(request.getSession().getServletContext().getRealPath("/")+file_name));
        try {
        	if("APP".equals(trade_type)){
        		 keyStore.load(instream, ConfigUtil.WECHAT_MCH_ID.toCharArray());
        	}else{
        		 keyStore.load(instream, ConfigUtil.WECHAT_WEB_MCH_ID.toCharArray());
        	}
           
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        char[] param = null;
        if("APP".equals(trade_type)){
        	param = ConfigUtil.WECHAT_MCH_ID.toCharArray();
	   	}else{
	   		param = ConfigUtil.WECHAT_WEB_MCH_ID.toCharArray();
	   	}
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore,  param)
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {

            HttpPost httpget = new HttpPost(ConfigUtil.WECHAT_REFUND_URL);
            StringEntity entity1 = new StringEntity(data);
            httpget.setEntity(entity1);
            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                /*if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                   
                }*/
                String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
               
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
	}
        

}
